package controllers;

import helpers.StringHelper;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import data.UserData;
import debugs.UserDebug;

import forms.CaptchaForm;
import forms.UserForm;

import models.UserModel;

public class ChangeProfileServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		TreeMap check = new TreeMap();
		UserModel user = (UserModel) request.getAttribute("user_logged_in");
		try {
			user = (UserModel) user.clone();
		} catch (CloneNotSupportedException e1) {
			//e1.printStackTrace();
		}
		
		user.setPassword("12345678");
		user.setRePassword("12345678");
		
		request.setAttribute("user", user);
		request.setAttribute("check", check);
		request.setAttribute("form", "changeProfile");
		
		try {
			request.getRequestDispatcher("/pages/form_user.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		HttpSession session = request.getSession();
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		UserData uData = new UserData();
		UserModel user = (UserModel) request.getAttribute("user_logged_in");
		String oldPassword = user.getPassword();
		try {
			user = (UserModel) user.clone();
		} catch (CloneNotSupportedException e1) {
			//e1.printStackTrace();
		}
		
		UserForm userForm = new UserForm();
		CaptchaForm captchaForm = new CaptchaForm();
		TreeMap forms = (TreeMap) userForm.checkValidProfile(request, user);
		user = (UserModel) forms.get("user");
		TreeMap check = (TreeMap) forms.get("checkValid");
		
		if (check.size() == 0) {
			if (user.getPassword().equalsIgnoreCase("12345678")) {
				user.setPassword(oldPassword);
			} else {
				user.setPassword(StringHelper.md5(user.getPassword()));
			}
			
			uData.insert(user);
			session.setAttribute("user_logged_in", user);
			user.setPassword("12345678");
			user.setRePassword("12345678");
			request.setAttribute("success", "Bạn đã thay đổi thông tin thành công.");
		}
		
		request.setAttribute("user", user);
		request.setAttribute("check", check);
		request.setAttribute("form", "changeProfile");
		
		try {
			request.getRequestDispatcher("/pages/form_user.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
